package com.nna88.voz.main;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.nna88.voz.contain.containPage3;
import com.nna88.voz.listview.listViewCustom3;
import com.nna88.voz.listview.listViewCustom3.OnActionItemClickListener;
import com.nna88.voz.quickaction.ActionItem;
import com.nna88.voz.quickaction.QuickAction;

public class Page3 extends Page{
	private ArrayList<containPage3> ListContains;
	private listViewCustom3 adapter;
	private int iPostType;
	private ArrayList<DownloadImage> listTaskDownloadImage;
	private String mTextTitle;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		listTaskDownloadImage = new ArrayList<DownloadImage>();
		ListContains = new ArrayList<containPage3>();
		adapter = new listViewCustom3(mActivity,ListContains);
	    adapter.setSize(mTextSize);
	    mList.setAdapter(adapter);
	    mTextTitle = getIntent().getStringExtra("TITLE");
	    mMenuTitle.setText(mTextTitle);
	    mParser.setUrl(URL+getIntent().getStringExtra("URL"));
	    sIdThread = getIDThread(mParser.getUrl());
	    mTask.execute(TASK_GETDOC);
	    
	    adapter.setOnActionItemClickListener(new OnActionItemClickListener() {

			@Override
			public void onItemClick(int pos, int actionId, View tv, int state) {
				// TODO Auto-generated method stub
				if(state == 0){
					if(mUser.isLogin())	ActionPopup(tv,pos);
				}else{
					GoPage(state);
				}

			}
		});
	    
	}
	@Override
	protected void GoPage(int state) {
		// TODO Auto-generated method stub
		super.GoPage(state);
		listTaskDownloadImage.clear();
	}
	private String getIDThread(String url){
		String temp = null;
		temp = "a";
		return temp;
	}
	void ActionPopup(final View arg1,final int pos){
	 	ActionItem replyItem 	= new ActionItem(1, "Reply", getResources().getDrawable(R.drawable.replyquickreply));
		ActionItem quoteItem 	= new ActionItem(2, "Quote", getResources().getDrawable(R.drawable.replyquote));
		ActionItem multiItem 	= new ActionItem(3, "Multi", getResources().getDrawable(R.drawable.replymultiquote_off));
		ActionItem editItem 	= new ActionItem(4, "Edit", getResources().getDrawable(R.drawable.replyedit));
		ActionItem deleteItem 	= new ActionItem(5, "Delete", getResources().getDrawable(R.drawable.replydelete));
		if(ListContains.get(pos).isMultiQuote()){
        	multiItem= new ActionItem(3, "Multi", 
        			getResources().getDrawable(R.drawable.replymultiquote_on));
    	}else{
    		multiItem 	= new ActionItem(3, "Multi",
    				getResources().getDrawable(R.drawable.replymultiquote_off));
    	}
	    QuickAction mQuickAction 	= new QuickAction(mContext);
		mQuickAction.addActionItem(replyItem);
		mQuickAction.addActionItem(quoteItem);
		mQuickAction.addActionItem(multiItem);
		
	    if(ListContains.get(pos).User().equals(mUser.User())){
	    	mQuickAction.addActionItem(editItem);
	    	mQuickAction.addActionItem(deleteItem);
	    }
		mQuickAction.show(arg1);
		mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(QuickAction quickAction, int position, int actionId) {
				//toast("actionId:"+String.valueOf(actionId)+";"+"position:"+String.valueOf(pos));
				
				if(actionId == 3){
					clickMultiQuote(pos);
				}else{
					if(actionId == 1){
						iPostType = REQUEST_REPLY;
						Parser(TASK_GETQUOTE);
					}
					else{
						if(actionId == 2) iPostType = REQUEST_QUOTE;
						else if(actionId == 4) iPostType = REQUEST_EDIT;
						else if(actionId == 5) iPostType = REQUEST_DELETE;
						mTask.cancel(true);
						mTask = new TaskGetHtml();
						mTask.execute(TASK_GETQUOTE,iPostType,Integer.parseInt(ListContains.get(pos).Id()));
					}
					
				}
			}
		});
	}
	private void clickMultiQuote(int index){
		if(mUser.isLogin() == true){
 			if(ListContains.get(index).isMultiQuote()){ 
 				ListContains.get(index).setMultiQuote(false);
     			String temp =mUser.cookies().get("vbulletin_multiquote").replace(
     										ListContains.get(index).Id(), "");
     			if(temp.contains("%2C") && temp.subSequence(0, 3).equals("%2C"))
     				temp = temp.substring(3, temp.length());
     			if(temp.contains("%2C")&& temp.subSequence(temp.length()-3, temp.length()).equals("%2C"))
     				temp = temp.substring(0, temp.length()-3);
     			if(temp.contains("%2C%2C"))
     				temp = temp.replace("%2C%2C", "%2C");
     			mUser.cookies().put("vbulletin_multiquote",temp);
     		}else{ 
     			ListContains.get(index).setMultiQuote(true);
     			if(mUser.cookies().containsKey("vbulletin_multiquote") != true){
	     			mUser.cookies().put("vbulletin_multiquote",
	     					ListContains.get(index).Id());
	     		}else{
	     			mUser.cookies().put("vbulletin_multiquote",
	     							mUser.cookies().get("vbulletin_multiquote")+"%2C"+
	     									ListContains.get(index).Id());		
	     		}
     		}
     		adapter.notifyDataSetChanged();
 		}else{
 			Toast.makeText(mContext, "Please Login", Toast.LENGTH_SHORT).show();
 		}
	}
	@Override
	protected void TaskCancle() {
		// TODO Auto-generated method stub
		super.TaskCancle();
		int size = listTaskDownloadImage.size();
		mTask.cancel(true);
		for(int i=0;i<size;i++){
			listTaskDownloadImage.get(i).Cancle();
		}
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//ListContains.clear();

	}
	@Override
	protected void updateSetFont(float value) {
		// TODO Auto-generated method stub
		super.updateSetFont(value);
		adapter.setSize(value);
		adapter.notifyDataSetChanged();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK){
			sPost = data.getExtras().getString("msg");
			switch (requestCode) {
			case REQUEST_QUOTE:
			case REQUEST_REPLY:
				mTask.cancel(true);
				mTask = new TaskGetHtml();
				mTask.execute(TASK_POSTREPLY);
				break;
			case REQUEST_EDIT:
				mTask.cancel(true);
				mTask = new TaskGetHtml();
				mTask.execute(TASK_POSTEDIT);
				break;
			default:
				break;
			}
		}
	}
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		updateSetFont(mTextSize);
	}
	@Override
	void Parser(int taskType) {
		super.Parser(taskType);
		if (doc == null) return;
		if(taskType == TASK_GETQUOTE){
			if(iPostType == REQUEST_DELETE){
				mTask.cancel(true);
				mTask = new TaskGetHtml();
				mTask.execute(TASK_POSTDELETE);
			}else{
				String mTextQuote = "";
				Intent i = new Intent(mContext, PageReply.class);
				Bundle extras = new Bundle();
				if(iPostType !=  REQUEST_REPLY){
					Element eleQuote = doc.select("textarea[name=message]").first();
					mTextQuote = eleQuote.textNodes().get(0).getWholeText();
				}
	 			extras.putString("msg",mTextQuote);
	 			extras.putFloat("textsize", mTextSize);
	 			i.putExtras(extras);
				startActivityForResult(i,iPostType);
			}
		}else{
			ListContains.clear();
	    	containPage3 mContain;
	    	Element mainElement;
	    	mainElement = doc.select("div[align=center]").get(1);
	    	Element eleLogin = mainElement.select("a[href=private.php]").first();
			//isSubscribe = isSubscribe();
	    	mTextNumPage.setText(parsePage(GO_INDEXPAGE));
	    	if(parsePage(GO_INDEXPAGE) !=  null)
	    		mMenuTitle.setText(mTextTitle+" - " + mTextNumPage.getText());
			if(eleLogin != null){
				String temp = mainElement.select("td[class=alt2]").get(0).select("a[href*=mem]").attr("href");
				temp = temp.split("=")[1];
				mUser.setUserId(temp);
		    	Element eleSecurity = mainElement.select("input[name*=securitytoken]").first();
		    	String secToken;
		    	secToken = eleSecurity.attr("value");
		    	mUser.setToken(secToken);
			}
			String m_user,m_time,m_AvatartUrl;
			Elements eleTag1s = mainElement.select("td[id*=td_post]");
	
			Iterator<Element> iteTag1 = eleTag1s.iterator();
			while(iteTag1.hasNext()){
				mContain = new containPage3();
				TaskDownloadImage mTask;
				Element eleTag1 = iteTag1.next();
				Element eleContain =  eleTag1.parent();
				Element eleAvatar = eleContain.previousElementSibling();
				Element eleTime = eleAvatar.previousElementSibling();
				m_AvatartUrl = eleAvatar.select("img[src*=avatars]").attr("src");
				m_user = eleAvatar.select("a[class=bigusername]").text();
				m_time = eleTime.text();
				Element elePostMessage = eleTag1.select("div[id*=post_message").first();
				if(elePostMessage!= null){
					mContain.setId(elePostMessage.attr("id").split("_")[2]);
			    	PaserPage3(elePostMessage,mContain,true,false);
					mContain.Info(m_user, m_time, null,m_AvatartUrl);
			    	//mTask = new TaskDownloadImage();
			    	listTaskDownloadImage.add(new DownloadImage(URL+m_AvatartUrl,
			    			"-99;"+String.valueOf(ListContains.size())));
					//new TaskDownloadImage().execute(URL+m_AvatartUrl,
			    	//		"-99;"+String.valueOf(ListContains.size()));
					ListContains.add(mContain);
				}
				adapter.notifyDataSetChanged();
			}
			if(listTaskDownloadImage.size() > 0)
				listTaskDownloadImage.get(0).Execute();
		}
	}
	class DownloadImage{
		TaskDownloadImage mTask;
		String url;
		String param;
		public DownloadImage( String url, String param){
			mTask = new TaskDownloadImage();
			this.url = url;
			this.param = param;
		}
		public void Execute(){
			mTask.execute(url,param);
		}
		public void Cancle(){
			mTask.cancel(true);
		}
	}
	class TaskDownloadImage extends AsyncTask<String, Void, String>{
		Bitmap bitmap;
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			//listTaskDownloadImage.add(this);
			InputStream in = null;
			URL mUrl;
			HttpURLConnection conn;
			String url = params[0];
        	try {
				mUrl = new URL(url);
				conn = (HttpURLConnection)mUrl.openConnection();
				conn.setDoInput(true);
				conn.connect();
				in = conn.getInputStream();
				if(in != null){	
					BitmapFactory.Options op = new Options();
					op.inSampleSize = 2;
					bitmap = BitmapFactory.decodeStream(in,null,op);
				}else 
					bitmap =  null;
				in.close();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return params[1];
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//listTaskDownloadImage.remove(this);
			String temp[] = result.split(";");
			int i = Integer.parseInt(temp[0]);
			int j = Integer.parseInt(temp[1]);
			if(i == -99){
				ListContains.get(j).setAvatar(bitmap);
			}else{
				ListContains.get(j).image.SetBitmap(i, bitmap);
				//ListContains.get(j).setAvatar(bitmap);
			}
			adapter.notifyDataSetChanged();
			listTaskDownloadImage.remove(0);
			if(listTaskDownloadImage.size() > 0)
				listTaskDownloadImage.get(0).Execute();
		}
		
	}
	private void PaserPage3(Element elePostMessage,containPage3 m_Contain,boolean write,boolean pre){
    	Element ele=null;
		if(elePostMessage.select("blockquote").first() != null){
			ele = elePostMessage.select("blockquote").first();
		}else{
			ele = elePostMessage;
		}
		if(ele != null){
			for (Node child : ele.childNodes()) {
				if(child instanceof Element){
					if(((Element)child).tagName().equals("div")){
						Element eleTemp = ((Element)child).select("div").first();
						m_Contain.addText("\n");
						PaserPage3(eleTemp,m_Contain,false,pre);
						m_Contain.addText("\n");
					}else if(((Element)child).tagName().equals("pre")){
						Element eleTemp = ((Element)child).select("pre").first();
						int start,end;
						start = m_Contain.getText().length();
						PaserPage3(eleTemp,m_Contain,false,true);
						end = m_Contain.getText().length();
						m_Contain.quote.add("", start,end);
					}else if(((Element)child).tagName().equals("ol")){
						Element eleTemp = ((Element)child).select("ol").first();
						PaserPage3(eleTemp,m_Contain,false,true);
					}else if(((Element)child).tagName().equals("li")){
						Element eleTemp = ((Element)child).select("li").first();
						PaserPage3(eleTemp,m_Contain,false,true);
					}else{
						if((((Element)child).select("table").first()) != null){
							Elements temp = ((Element)child).select("table");
							Element temp2,temp3;
							temp2 = temp.select("td[style*=border:1px inset]").first();
							if(temp2 != null){
								temp3 = temp2.select("div[style*=font-style:italic]").first();
								if(temp3!= null){
									int start,end;
									start = m_Contain.getText().length();
									m_Contain.addText(temp3.previousElementSibling().text() + "\n");
									PaserPage3(temp3,m_Contain,false,pre);
									end = m_Contain.getText().length();
									m_Contain.quote.add("", start, end);
									
								}else{
									int start,end;
									start = m_Contain.getText().length();
									PaserPage3(temp2,m_Contain,false,pre);
									end = m_Contain.getText().length();
									m_Contain.quote.add("", start, end);
								}
							}
						}else if(((Element)child).tagName().equals("img")){
							int start,end;
							String urlImage = (((Element)child).select("img[src]").attr("src"));
							if(urlImage.subSequence(0, 21).equals("http://vozforums.com/"))
								urlImage = urlImage.substring(21);
							if(urlImage.substring(0, 1).equals("/"))
								urlImage = urlImage.substring(1, urlImage.length());
							
							start = m_Contain.getText().length();
							end = start + 2;
							
							if(!(urlImage.contains("http://")||urlImage.contains("https://")))
								m_Contain.image.add(urlImage, start, end, loadBitmapAssert(urlImage));
							else{
								m_Contain.image.add(urlImage, start, end, loadBitmapAssert("google.png"));
								listTaskDownloadImage.add(new DownloadImage(urlImage,
										String.valueOf(m_Contain.image.sizeBitmap()-1)+";"+
						    			String.valueOf(ListContains.size())));
							}
							m_Contain.addText("aa");
							
						}else if(((Element)child).tagName().equals("br")){
							m_Contain.addText("\n");
						}else if(((Element)child).tagName().equals("b")){
							Element eleTemp = ((Element)child).select("b").first();
							int start,end;
							start = m_Contain.getText().length();
							PaserPage3(eleTemp,m_Contain,false,pre);
							end = m_Contain.getText().length();
							m_Contain.type.add("", start, end,Typeface.BOLD_ITALIC);
						}else if(((Element)child).tagName().equals("u")){
							Element eleTemp = ((Element)child).select("u").first();
							int start,end;
							start = m_Contain.getText().length();
							PaserPage3(eleTemp,m_Contain,false,pre);
							end = m_Contain.getText().length();
							m_Contain.typeU.add("", start, end);
						}else if(((Element)child).tagName().equals("font")){
							Element eleTemp = ((Element)child).select("font").first();
							int start,end;
							String mfont="while",msize="3";
							if(((Element)child).select("font[color]").first()!=null) 
								mfont = ((Element)child).select("font[color]").attr("color");
							if(((Element)child).select("font[size]").first()!=null) 
								msize = ((Element)child).select("font[size]").attr("size");
							start = m_Contain.getText().length();
							PaserPage3(eleTemp, m_Contain,false,pre);
							end = m_Contain.getText().length();
							m_Contain.font.add("", start, end, mfont, Integer.parseInt(msize));
						}else if (((Element)child).tagName().equals("a")){
							String temp = ((Element)child).select("a[href]").attr("href");
							if(temp.contains("mailto:")){
								temp = temp.substring(7, temp.length());
							}else{
								temp = temp.substring(temp.indexOf("http"), temp.length());
							}
							temp=temp.replace("%3A",":");
							temp=temp.replace("%2F","/");
							temp=temp.replace("%3F","?");
							temp=temp.replace("%3D", "=");
							temp=temp.replace("%26", "&");
							int start,end;
							String tempText = ((Element)child).select("a[href]").text();
							start = m_Contain.getText().length();
							end = start + tempText.length();
							m_Contain.web.add(temp, start, end);
							m_Contain.addText(tempText);
						}else{
							m_Contain.addText(((Element)child).text());
							if(pre) m_Contain.addText("\n");
						}
					}
				}
			    if (child instanceof TextNode) {
			    	
			    	if(pre) m_Contain.addText(((TextNode) child).getWholeText());
			    	else m_Contain.addText(((TextNode) child).text());
			    }
			}
		}else{
			m_Contain.addText(elePostMessage.text());
		}
    }

}
